import { defineStore } from "pinia";
import axios from "axios";
import { nanoid } from "nanoid";

// 配置项写法：actions、state都是配置项
// export const useTalkStore = defineStore("talkStore", {
//   actions: {
//     async getATalk() {
//       let result = await axios.get("https://api.shadiao.pro/chp");
//       // console.log(result.data.data.text);

//       let obj = { id: nanoid(), title: result.data.data.text };
//       console.log(obj);
//       this.talkList.unshift(obj);
//     },
//   },

// // state 数据的存储位置
//   state() {
//     return {
//       // talkList: [
//       //   { id: "00001", title: "土味情话一" },
//       //   { id: "00002", title: "土味情话二" },
//       //   { id: "00003", title: "土味情话三" },
//       // ],

//       talkList: JSON.parse(localStorage.getItem("talklist") as string) || [],
//     };
//   },
// });

// 组合式写法
import { reactive } from "vue";
export const useTalkStore = defineStore("talkStore", () => {
  // 定义数据
  let talkList = reactive(
    JSON.parse(localStorage.getItem("talklist") as string) || []
  );

  // 方法
  async function getATalk() {
    let result = await axios.get("https://api.shadiao.pro/chp");
    // console.log(result.data.data.text);

    let obj = { id: nanoid(), title: result.data.data.text };
    console.log(obj);
    talkList.unshift(obj);
  }

  // 返回
  return { talkList, getATalk };
});
